# ** Header **
# Modify sys.path variable in order to enable direct module loading
# from folder "third_party/"
import os, sys
run_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(run_path, "third_party"))

# Load ITF
import config
from backend import dbconnection
from backend import session

# Import 3rd party scripts
import BitTornado
from Cheetah.Template import Template
import cherrypy


# ** Body **
class ITF:
    """ @@cherrypy """
    @cherrypy.expose
    def index(self, **kwargs):
        """
            foobar
        """
        if session.isLoggedIn():
            return "joo, eingeloggt!"
        else:
            t = Template(file="templates/devel/login.html", searchList=[{}])
            return t.respond()

        cherrypy.session['foobar'] = "fdsf"
        return cherrypy.session.get("foobar")

    @cherrypy.expose
    def login(self, username, password, **kwargs):
        """
            foobar
        """
        if session.login(username, password):
            return "logged in"
        else:
            return "wrong user/password combination"

    @cherrypy.expose
    def logout(self, **kwargs):
        """
            foobar
        """
        if session.logout():
            return "deleted cookies"
        else:
            return "couldnt log you out"
        #return "not safe yet -> logout disabled"



# Integrate module MySQLdb safely into CherryPy
cherrypy.engine.on_start_thread_list = [dbconnection.connect]
# Read settings from database and apply them
dbconnection.collectSettings()
cherrypy.config.update("backend/httpd.conf")
# Mount ITF applications
if config.DEVEL_MODE:
    cherrypy.tree.mount(dbconnection.DBTest(), dbconnection.DBTest.__mount_point__)

# Start CherryPy
cherrypy.quickstart(ITF(), config="backend/engine.conf")

# ** Footer **
